#include "getfilename.h"


int epoll_loop(int *efd,int *sfd)
{
    FILE *fd;
    int i;
    umask(0);
    fd = fopen("./test.txt", "a+");
    struct epoll_event ev, events[500];
    ev.data.fd=*sfd;
    ev.events=EPOLLIN;
    epoll_ctl(*efd, EPOLL_CTL_ADD, ev.data.fd, &ev);
    int n=0, count=0;
    socklen_t len=sizeof(struct sockaddr_in);
    struct sockaddr_in serveraddr;
    bzero(&serveraddr, len);
    myefd ap;
    myefd *head_person=NULL, *subnod=NULL;
    pthread_mutex_init(&ap.mutex_count, NULL);
    while(1)
    {
        n=epoll_wait(*efd, events, 500, 0);
        for(i=0;i<n;i++)
        {
            if(events[i].data.fd==*sfd)
            {
                int *cfd = calloc(sizeof(int), 1);
                *cfd=accept(*sfd, (struct sockaddr *)&serveraddr, &len);
                pthread_attr_t pthread_attr;
                pthread_attr_setdetachstate(&pthread_attr, PTHREAD_CREATE_DETACHED);
                pthread_t pid;
                ap.c_sum=&count;
                pthread_mutex_lock(&ap.mutex_count);
                count++;
                pthread_mutex_unlock(&ap.mutex_count);
                ap.efd=efd;
                ap.sfd=sfd;
                ap.fd=cfd;
                bzero(ap.ip,sizeof(ap.ip));
                strcpy(ap.ip,inet_ntoa(serveraddr.sin_addr));
                if(head_person!=NULL)
                {
                    subnod->next=calloc(sizeof(myefd),1);
                    subnod=subnod->next;
                    subnod->next=NULL;
                    subnod->head=head_person;
                }
                else
                {
                    head_person=calloc(sizeof(myefd),1);
                    head_person->next=NULL;
                    subnod=head_person;
                }
                subnod->head=head_person;
                subnod->c_sum=ap.c_sum;
                subnod->efd=ap.efd;
                subnod->sfd=ap.sfd;
                subnod->fd=ap.fd;
                strcpy(subnod->ip, ap.ip);

                fscanf(fd, "%d %s\n", &subnod->id, subnod->name);
                pthread_create(&pid, &pthread_attr, rdata, (void*)subnod);
            }
        }
    }
    fclose(fd);
    return 0;
}
